package com.jsb.laundry.config.properties;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.jsb.laundry.common.utils.JSBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.jsb.laundry.config.properties.OSSProperties.*;

@Component
public class AliOSSUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(AliOSSUtil.class);

    /**
     * 上传文件
     *
     * @param file
     * @param repositoryPath 桶内路径
     * @return
     */
    public static String uploadFile(MultipartFile file, String repositoryPath) {
        // 文件后缀
        String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//        String ext = "." + FilenameUtils.getExtension(file.getOriginalFilename());
        // 文件存储相对路径
        String fileInnerPath = repositoryPath + "/" + JSBUtil.generateUUID() + ext;
//        String fileInnerPath = repositoryPath + "/" + file.getOriginalFilename();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            LOGGER.info("文件桶内位置：" + fileInnerPath);
            ossClient.putObject(bucketName, fileInnerPath, file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return host + "/"+ fileInnerPath;
    }

    /**
     * 批量上传
     *
     * @param files
     * @param repositoryPath
     * @return
     */
    public static List<String> batchUploadImg(List<MultipartFile> files, String repositoryPath) {
        List<String> urls = new CopyOnWriteArrayList<>();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            for (MultipartFile file : files) {
                // 文件后缀
                String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                // 文件存储相对路径
                String fileInnerPath = repositoryPath + "/" + JSBUtil.generateUUID() + ext;
                LOGGER.info("文件桶内位置：" + fileInnerPath);
                ossClient.putObject(bucketName, fileInnerPath, file.getInputStream());
                urls.add(host + fileInnerPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return urls;
    }

}
